--
-- @Author:      
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 消息的派发

local skynet = require "skynet"
-- local queue = require "skynet.queue"



local MessageDispatch = class("MessageDispatch")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageDispatch:ctor()
	self.default_callback = nil
	self.messages = {} --本服务要监听的消息
	
	self:register('hotfix', handler(self, self.hotfixFile))	--热更文件
end

-- 注册本服务消息
function MessageDispatch:registerDefault(callback)
	self.default_callback = callback
end

--注册本服务里的消息
function MessageDispatch:register(msg_name, callback)
	if not msg_name then 
		return 
	end
	if not callback or type(callback) ~= 'function' then 
		g.Log():error("注册的函数回调不对___", msg_name)
		return
	end
	self.messages[msg_name] = callback
end

--服务器消息派发
function MessageDispatch:dispatchMessage(session, source, cmd, ... )
	-- print("####dispatchMessage#######",session,source, cmd, ...)
	local func = self.messages[cmd] -- 
	if not func and not self.default_callback then 
		g.Log():error("####### cmd "..cmd .." not found at service ", ...)		
		return
	end

	local ok = nil
	local res = false
	if func then
		if not session and not source then 
			--不是服务发来的消息
			return func(...)
		end
		ok, res = xpcall(func, debug.traceback, ...)	
	else
		ok, res = xpcall(self.default_callback, debug.traceback, cmd, ...) 	
	end
	if not ok then 
		print("_____2____dispatchMessage___error___", cmd, ... , res)
		return 
	end	
	skynet.retpack(res)
end

function MessageDispatch:dispatch()
	return handler(self, self.dispatchMessage)
end

function MessageDispatch:hotfixFile(file_name)
    g.Log():debug("____hotfix_____", file_name )
    return g.hotfix:hotfixFile(file_name)
end 

return MessageDispatch